/**  用户 */

const { createCartUsersService, deleteCartUsersService, putCartUsersService, getCartUsersService } = require('../service/cartUsersService.js')
const { userRegisterError } = require('../constant/err.type')

class CartUsersController {

    // 新增
    async createCartUsers(ctx, next) {
        const { name, nickname, email, phone } = ctx.request.body

        try {
            const res = await createCartUsersService({ name, nickname, email, phone })

            ctx.body = {
                code: 0,
                data: res,
                message: 'success'
            }
        } catch (error) {
            console.log(err)
            ctx.app.emit('error', userRegisterError, ctx)
        }

    }

    /**  删除 */
    async deleteCartUsers(ctx, next) {
        const { userId } = ctx.query
        if (!userId) return

        try {
            const res = await deleteCartUsersService({ userId })

            ctx.body = {
                code: 0,
                message: '成功',
                data: res
            }
        } catch (error) {
            ctx.app.emit('error', userRegisterError, ctx)
        }

    }


    /**  修改 putCartUsersService */
    async putCartUsers(ctx, next) {
        const { userId, name, nickname, email, phone } = ctx.request.body
        if (!userId) return

        try {
            const res = await putCartUsersService({ userId, name, nickname, email, phone })

            ctx.body = {
                code: 0,
                data: res,
                message: '成功'
            }
        } catch (error) {
            ctx.app.emit('error', userRegisterError, ctx)
        }

    }


    /**  查询 */
    async getCartUsers(ctx, next) {
        console.log(6666);
        const { name, nickname, email, phone, pageCurrent, pageSize } = ctx.query
        const params = {}
        // 短路运算
        name && Object.assign(params, { name })  // 不为空则添加到whereOpt中
        nickname && Object.assign(params, { nickname })  // 不为空则添加到whereOpt中
        email && Object.assign(params, { email })  // 不为空则添加到whereOpt中
        phone && Object.assign(params, { phone })  // 不为空则添加到whereOpt中
        pageCurrent && Object.assign(params, { pageCurrent: parseInt(pageCurrent) })  // 不为空则添加到whereOpt中
        pageSize && Object.assign(params, { pageSize: parseInt(pageSize) })  // 不为空则添加到whereOpt中

        try {
            // 调用service层最好加try catch
            const { data, total, pageSize, pageCurrent } = await getCartUsersService(params)
            // 3.返回给客户端
            ctx.body = {
                code: 0,
                message: 'success',
                data: {
                    data,
                    total,
                    pageSize,
                    pageCurrent
                }
            }
        } catch (error) {
            ctx.app.emit('error', userRegisterError, ctx)
        }
    }


}

module.exports = new CartUsersController()